package com.example.eback.service;

import com.example.eback.constans.ProjCode;
import com.example.eback.dao.ProjectDAO;
import com.example.eback.dao.user_projDAO;
import com.example.eback.entity.Proj.Project;
import com.example.eback.entity.Proj.user_proj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProjService {

    @Autowired
    private ProjectDAO projectDAO;
    @Autowired
    private user_projDAO user_projDAO;

    public List<Project> getProjByUidAndPermission(int uid, String permission){
        List<user_proj> userProjList=new ArrayList<>();
        if ("not".equals(permission)) {
            return  null;
        } else if ("all".equals(permission)) {
            userProjList=user_projDAO.findByUidAndPermissionNotInOrderByTimeDesc(uid, "not");
        } else {
            userProjList= user_projDAO.findByUidAndPermissionOrderByTimeDesc(uid, permission);
        }
        List<Integer> ids=new ArrayList<>();
        for(user_proj userProj:userProjList){
            ids.add(userProj.getUid());
        }
        return  projectDAO.findByIdIn(ids);
    }

    public Project findById(int id){
        return  projectDAO.findById(id).orElse(null);
    }

    public Project save(Project project){
        return  projectDAO.save(project);
    }

    public ProjCode delete(int pid,int uid){
        Project project;
        project=findById(pid);
        if (project==null )
            return ProjCode.NOT_EXIST;
        user_proj userProj = user_projDAO.findAllByUidAndPidAndPermission(uid, pid, "admin");
        if(userProj==null){
            return  ProjCode.DELETE_NOT_PER;
        }
        projectDAO.deleteById(userProj.getPid());
        user_projDAO.delete(userProj);
        return ProjCode.DELETE_SUCCESSFUL;
    }
}
